
<template>
    <div class="pres-comp-ingredient-comp">
         <TitleBox type=2>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -20}">Ingredient</span>
            </template>
        </TitleBox>

        <!-- TODO 3个echart -->
        <div class="chart-box" ref="ingrCompDiv">
            <div class="chart-img-wrap chart-img-wrap-down">
                <uiEchart :config="optionHia" :vt="dataObj.echartoptVt1" ref="chartHia"/>
            </div>
             <div class="chart-img-wrap">
                <uiEchart :config="optionbbb" :vt="dataObj.echartoptVt1" ref="chartbbb"/>
            </div>

            <div class="chart-img-wrap">
                <uiEchart :config="optioncaco2" :vt="dataObj.echartoptVt1" ref="chartcaco2"/>
            </div>
            <div class="chart-img-wrap">
                <uiEchart :config="optionhob" :vt="dataObj.echartoptVt1" ref="charthob"/>
            </div>
        </div>

        <div class="condition-box">
            <div class="condition-left search-cond-left">
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -44}">List sort</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-radio-group v-model="condObj.sort" @change="toSearch">
                                <div class="cond-radio-wrap">
                                    <el-radio class="cond-radio-item" value="Asc"><span v-lang="{lang: controlSto.language, lgid: -49}"></span></el-radio>
                                    <el-radio class="cond-radio-item" value="Desc"><span v-lang="{lang: controlSto.language, lgid: -50}"></span></el-radio>
                                </div>
                            </el-radio-group>
                        </div>
                    </template>
                </SearchDrop>

                <!-- <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -75}">Metabolic stablility</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.metabolicStability">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in metabolicStabilityList" :key="'metstab_' + item.id" :value="item.metabolicStabilityCode" :label="item.metabolicStabilityName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>

                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -76}">Transport mode</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.transportMode">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in transportModeList" :key="'transmode_' + item.id" :value="item.transportModeCode" :label="item.transportModeName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>

                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -77}">Half-life period</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.halfLifePeriod">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in halfLifePeriodList" :key="'halfperiod_' + item.id" :value="item.halfLifePeriodCode" :label="item.halfLifePeriodName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>        -->
                <SearchDrop class="cond-item">
                    <template #title>
                        <span>hia</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.hia" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in ingreCheackList" :key="'hia_' + item.id" :value="item.id" :label="item.name"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <span>bbb</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.bbb" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in ingreCheackList" :key="'bbb_' + item.id" :value="item.id" :label="item.name"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <span>Caco2</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.Caco2" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in ingreCheackList" :key="'Caco2_' + item.id" :value="item.id" :label="item.name"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <span>Hob</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox-group v-model="condObj.Hob" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in ingreCheackList" :key="'Hob_' + item.id" :value="item.id" :label="item.name"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
            </div>
            <div class="condition-right">
                <div class="ipt-cont">
                    <el-input class="ipt-search" clearable="true" v-model="condObj.searchword" autofocus :placeholder="searchPlace" />
                </div>
                <SearchBtn class="search-item" @click.stop="toSearch"/>

                <TableFilter class="search-item" :column="dataObj.columnList" :filterKey="condObj.filterKey" @onChg="chgTableCol"/>

                <SearchLoad type='prescriptionIngredient' :uiCode="condObj.uiCode" :para="{
                    'content': condObj.searchword,
                    'ingrBbb': condObj.bbb.join(','),
                    'ingrCaco2': condObj.Caco2.join(','),
                    'ingrHia': condObj.hia.join(','),
                    'ingrHob': condObj.Hob.join(','),
                    'langCode': controlSto.language == 1 ? 'ENG' : 'CHN',
                    'sortType': condObj.sort,
                    'uiTypeCode': condObj.uiCode,
                    'prescriptionId': detailId
                }"/>
            </div>
        </div>


        <div class="cont-box">
            <uiTable
                :config="dataObj.tableConfig"
                :columnConfig="dataObj.columnConfig" 
                :data="dataObj.dataList"
                :loading="isLoading"
                :key="dataObj.searchTablevt">
                <template #[condObj.idField]="{ row }">
                    <div class="jump-box" @click.stop="toClkItem(row, 1)"><span>{{row[condObj.idField]}}</span></div>
                </template>
                <template #[condObj.ingrNameField]="{ row }">
                    <div class="jump-box" @click.stop="toClkItem(row, 1)"><span>{{row[condObj.ingrNameField]}}</span></div>
                </template>
                <template #[condObj.herbNameField]="{ row }">
                    <el-tooltip placement="top" :content="row[condObj.herbNameField]">
                        <div class="jump-box herb-jump-name" @click.stop="toClkItem(row, 2)"><span>{{row[condObj.herbNameField]}}</span></div>
                    </el-tooltip>
                </template>
            </uiTable>
            <div class="page-box" v-if="condObj.total > 10">
                <uiPagination
                    :total="condObj.total" :pageSize="condObj.pageSize" :pageIndex="condObj.pageIndex"
                    @onSizeChange="chgSize" @onCurrentChange="chgCurrnt"/>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch } from 'vue'
    import { useIntersectionObserver } from '@vueuse/core';
    import TitleBox from '@/components/TitleBox.vue'
    import SearchBtn from '@/components/SearchBtn.vue'
    import uiEchart from '@/components/ui-echart.vue'
    import TableFilter from '@/components/TableFilter.vue'
    import SearchLoad from '@/components/SearchLoad.vue'
    import SearchDrop from '@/components/SearchDrop.vue'
    import uiTable from '@/components/ui-table.vue'
    import uiPagination from '@/components/ui-pagination.vue'
    import { useRouter } from 'vue-router'

    import { langTxt, getFilterThArr, getFilterLangArr, computedgraphOptions } from '@/utils/util'
    import { getTableThList, getPrescriptionCompIngr, getPrescriptionIngredientStatistic, herbAll } from '@/service/tcm'
    
    import { ingreCheackList } from '@/utils/database'
    import { controlStore } from '@/stores/control'
    import { debounce } from 'lodash'
    
    const emitter = defineEmits(['toCalc']);
    const controlSto = controlStore();
    const router = useRouter();
    const ingrCompDiv = ref(null)
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
    const chartHia = ref(null), chartbbb = ref(null), chartcaco2 = ref(null), charthob = ref(null);
    let optionHia = computedgraphOptions(langTxt(controlSto.language, '-103'), '', [], true, 'center', '80%', ['50%', '50%'], '', '', 'center');
    let optionbbb = computedgraphOptions(langTxt(controlSto.language, '-104'), '', [], true, 'center', '80%', ['50%', '50%'], '', '', 'center');
    let optioncaco2 = computedgraphOptions(langTxt(controlSto.language, '-105'), '', [], true, 'center', '80%', ['50%', '50%'], '', '', 'center');
    let optionhob = computedgraphOptions(langTxt(controlSto.language, '-106'), '', [], true, 'center', '80%', ['50%', '50%'], '', '', 'center');
    let searchDebounce = null;

    
    const isLoading = ref(true);

    const condObj = reactive({
        idField: '100716826576557090',
        ingrNameField: '100716826576557091',
        herbNameField: '100716826576556883',
		searchword: '',
		filterKey: 'pres3',
        uiCode: 'prescription_composition_ingredient',
		sort: 'Asc',
        halfLifePeriod: [],
        transportMode: [],
        metabolicStability: [],
        hia: ['0', '1'],
        bbb: ['0', '1'],
        Caco2: ['0', '1'],
        Hob: ['0', '1'],
        word: '',
		sortType: 'Asc',
        halfLifePeriodStr: [],
		transportModeStr: [],
		metabolicStabilityStr: [], 
        total: 0,
        pageSize: 10,
        pageIndex: 1,
	});

	const dataObj = reactive({
		searchTablevt: 1,
		echartoptVt1: 1,
		columnList: [],
		tableConfig: {
			// size: 'small',
			'tooltip-effect': 'dark',
			'highlight-current-row': true,
			stripe: true,
			'header-cell-style': { background: '#BC9F77', color: '#FFF' },
		},
		columnConfig: [],
		dataList: []
	});

    const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});
    


    onBeforeMount(()=> {
        const {stop} = useIntersectionObserver(
            ingrCompDiv,
            ([{ isIntersecting }], observerElement) => {
                if (isIntersecting) {
                    // 停止监听，如果你只想知道一次可视性变化
                    getTableTh(); 
                    initDebounce();
                    toGetData();
                    toGetPrescriptionIngredientStatistic();
                    //阻止再次请求
                    stop()
                }
            },
            {
                threshold: 0, // 当交叉框达到视窗的这部分时触发
            }
        );
    });

    const initDebounce = () => {
        searchDebounce = debounce((e) => {
           getDataList();
        }, 400);
    };
    const toClkItem = (row, type) => {
        // router.push({ name: 'herbdetail' , query: {id: row[condObj.idField]} });
        if(type == 1) {
			router.push({ name: 'ingrdetail' , query: {id: row[condObj.idField]} });
		} else {
			herbAll({langCode: controlSto.language == 1 ? 'ENG' : 'CHN', name: row[condObj.herbNameField]}).then(res => {
				if(res.success && res.data) {
                    res.data.forEach(e => {
                        if(row[condObj.herbNameField] === e.name) router.push({ name: 'herbdetail' , query: {id: e.code} });
                    })
				}
			})
		}
    }
    const toGetPrescriptionIngredientStatistic = () => {
        const param = {
            prescriptionId: detailId.value,
            content: condObj.searchword
        }
        getPrescriptionIngredientStatistic(param).then(res => {
            if(res.success) {
                let bbb = [],caco2 = [], hia = [], hob = [];
                for(let key in res.data.ingrBbb) {
                    bbb.push({value: res.data.ingrBbb[key], name: key})
                }
                optionbbb.series[0].data = bbb;
                optionbbb.title.text = langTxt(controlSto.language, '-104');
                optionbbb.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                chartbbb.value.initEchart();
                for(let key in res.data.ingrCaco2) {
                    caco2.push({value: res.data.ingrCaco2[key], name: key})
                }
                optioncaco2.series[0].data = caco2;
                optioncaco2.title.text = langTxt(controlSto.language, '-105');
                optioncaco2.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                chartcaco2.value.initEchart();
                for(let key in res.data.ingrHia) {
                    hia.push({value: res.data.ingrHia[key], name: key})
                }
                optionHia.series[0].data = hia;
                optionHia.title.text = langTxt(controlSto.language, '-103');
                optionHia.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                chartHia.value.initEchart();
                for(let key in res.data.ingrHob) {
                    hob.push({value: res.data.ingrHob[key], name: key})
                }
                optionhob.series[0].data = hob;
                optionhob.title.text = langTxt(controlSto.language, '-106');
                optionhob.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                charthob.value.initEchart();
            }
        })
    }
    const getTableTh = () => {
        let params = {
            uiCode: condObj.uiCode,
            langCode: 'ENG,CHN'
        };
        getTableThList(params).then((res) => {
            if (res.success) {
                let arr = res.data || [];
                let thArr = getFilterThArr(arr, dataObj.filterKey);
        		let langArr = getFilterLangArr(thArr);
        		controlSto.setLangList(langArr);
        		dataObj.columnList = thArr;
            }
        }).catch(() => {});
    };

    const chgTableCol = (e) => {
		dataObj.columnConfig = e || [];
		dataObj.searchTablevt = new Date().valueOf();
        emitter('toCalc');
    };

    
    const toGetData = () => {
        searchDebounce && searchDebounce();
    };

    const getDataList = () => { // getPrescriptionCompIngr

        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
            prescriptionId: detailId.value,
            content: condObj.word,
            // TransportMode: condObj.transportModeStr || '',
            // halfLifePeriod: condObj.halfLifePeriodStr || '',
            // metabolicStability: condObj.metabolicStabilityStr || '',
            uiTypeCode: condObj.uiCode,
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1,
            ingrBbb: condObj.bbb.join(','),
            ingrCaco2: condObj.Caco2.join(','),
            ingrHia: condObj.hia.join(','),
            ingrHob: condObj.Hob.join(','),
            sortType: condObj.sort
        };
        isLoading.value = true;
        getPrescriptionCompIngr(params).then((res) => {
            isLoading.value = false;
            if (res.success && res.data && res.data.records) {
                dataObj.dataList = res.data.records || [];
                condObj.total = res.data.totalCount || 0;

                console.log(dataObj.dataList, '---->>>>>')
            }
        }).catch(() => {
            isLoading.value = false;
        });

        emitter('toCalc');

    };


        
    const chgSize = (e) => {
        condObj.pageSize = e || 10;
        toGetData();
    };
    const chgCurrnt = (e) => {
        condObj.pageIndex = e || 1;
        toGetData();
    };
    const toSearch = () => {
        condObj.word = condObj.searchword;
        condObj.sortType = condObj.sort;
        condObj.halfLifePeriodStr = condObj.halfLifePeriod.join(',');
        condObj.transportModeStr = condObj.transportMode.join(',');
        condObj.metabolicStabilityStr = condObj.metabolicStability.join(',');
        condObj.pageIndex = 1;
        toGetData();
    };
    
    watch(() => controlSto.language, (nv, ov) => {
		if(nv != ov && ov) {
			dataObj.echartoptVt1 = new Date().valueOf();
            toGetData();
            toGetPrescriptionIngredientStatistic();
		}
	}, { immediate: true });


</script>


<style lang="scss" scoped>
    .pres-comp-ingredient-comp {
        padding-bottom: 24px;
        .chart-box {
            display: flex;
            justify-content: space-between;
            margin-top: 24px;
            .chart-img-wrap {
                height: 240px;
                width: 32%;
                margin: 0 12px;
                // padding: 8px 12px 0;
            }
        }
        .condition-box {
            display: flex;
            padding: 30px 0 22px;
            justify-content: space-between;
            // border: 1px solid red;
            // .condition-left {
            //     .cond-item {
            //         margin-right: 16px;
            //     }
            // }
            .condition-left {
                .cond-item {
                    margin-right: 16px;
                    margin-bottom: 8px;
                }
            }
            .condition-right {
                .ipt-cont {
                    display: inline-block;
                    padding-right: 16px;
                    .ipt-search {
                        // width: 300px;
                    }
                }
                .search-item {
                    margin-right: 16px;
                }
            }
        }
        .cont-box {
            .herb-jump-name {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
    }
</style>
